<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2022/11/24
 * Time: 14:21
 */
namespace app\index\controller;

use app\index\service\DyOpenService;
use app\index\service\KsOpenService;
use app\index\service\PayService;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use WeChat\Contracts\Tools;

class Notify{


    /**
     * 抖音支付订单回调
     * @return string
     */
    public function dyPayOrderNotify(){
        Log::info('支付回调');
        $service = new DyOpenService();
        $notify = request()->param();
        try {
            if ($notify['type'] !== 'payment') {
                Log::info('回调验证错误-type类型不是payment');
                return 'fail';
            }
            if ($notify['msg_signature'] !== $service->getNotifySign($notify)) {
                Log::info('回调验证错误-验证签名失败');
                return 'fail';
            } else {
                //获取订单信息
                $data = json_decode($notify['msg'], true);
                Log::info('验签通过：'.$data['cp_orderno']);
                //处理订单
                $order_no = $data['cp_orderno'];
                $order = Db::name('pay_order')
                    ->where('order_no', $order_no)
                    ->find();
                //更新订单状态到已支付
                Db::name('pay_order')
                    ->where('id',$order['id'])
                    ->update([
                        'is_pay'=>1,
                        'status' => 10,
                        'out_trade_no' => $data['order_id'],
                        'pay_at'=>currentTime()
                    ]);
                $user = Db::name('user')
                    ->where('id',$order['user_id'])
                    ->find();

                //推送订单到抖音
                $service->pushOrder($user['dy_openid'],$order['order_no'],$order['id'],strtotime($order['create_at']),$order['pay_money'],$order['order_name']);
                $data = ['err_no' => '0', 'err_tips' => 'success'];
                return json($data);
            }
        }catch (Exception $e){
            Log::info('发生异常：'.$e->getMessage());
            Log::info('发生异常：'.$e->getTraceAsString());
            return 'fail';
        }
    }


    /**
     * 微信支付订单回调
     * @return string
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wxPayOrderNotify(){
        $payService = new PayService();
        $result = $payService->weNotify();
        if($result){
            //说明验签成功
            //处理订单
            $order_no = $result['out_trade_no'];
            $order = Db::name('pay_order')
                ->where('order_no', $order_no)
                ->find();
            //获取用户的解锁的信息
            $unlock_info = json_decode($order['unlock_info'],true);
            foreach ($unlock_info as $k=>$v){
                //首先判断该城市的解锁信息是否存在
                $user_unlock = Db::name('user_unlock_region')
                    ->where('user_id',$order['user_id'])
                    ->where('region_name',$v['city'])
                    ->find();
                if(empty($user_unlock)){
                    //不存在的话则进行添加
                    $temp['user_id'] = $order['user_id'];
                    $temp['region_name'] = $v['city'];
                    $temp['is_unlock_question'] = $v['is_unlock_question'];
                    $temp['is_unlock_skill'] = $v['is_unlock_skill'];
                    $temp['create_at'] = currentTime();
                    Db::name('user_unlock_region')->insert($temp);
                }else{
                    //存在的时候直接进行更新
                    if($user_unlock['is_unlock_question'] == 0) {
                        $temp['is_unlock_question'] = $v['is_unlock_question'];
                    }
                    if($user_unlock['is_unlock_skill'] == 0) {
                        $temp['is_unlock_skill'] = $v['is_unlock_skill'];
                    }
                    $temp['update_at'] = currentTime();
                    Db::name('user_unlock_region')
                        ->where('id',$user_unlock['id'])
                        ->update($temp);
                }
            }
            //更新订单状态到已支付
            Db::name('pay_order')
                ->where('id',$order['id'])
                ->update(['is_pay'=>1,'pay_at'=>currentTime()]);
            ob_clean();
            return Tools::arr2xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
        }else{
            return 'fail';
        }
    }


    /**
     * 快手回调
     * @return string|\think\response\Json
     */
    public function ksPayOrderNotify(){
        Log::info('快手支付回调');
        $service = new KsOpenService();
        $notify = request()->param();
        Log::info('返回的参数：'.json_encode($notify));
        try {
            if ($notify['biz_type'] !== 'PAYMENT') {
                Log::info('回调验证错误-type类型不是payment');
                return 'fail';
            }
            $kwaisign = request()->header('kwaisign');
            Log::info('返回的签名：'.$kwaisign);
            if ($kwaisign !== $service->getNotifySign($notify)) {
                Log::info('回调验证错误-验证签名失败');
                return 'fail';
            } else {
                //获取订单信息
                $data = $notify['data'];
                Log::info('验签通过：'.$data['out_order_no']);
                //处理订单
                $order_no = $data['out_order_no'];
                $order = Db::name('pay_order')
                    ->where('order_no', $order_no)
                    ->find();
                //获取用户的解锁的信息
                $unlock_info = json_decode($order['unlock_info'],true);
                foreach ($unlock_info as $k=>$v){
                    //首先判断该城市的解锁信息是否存在
                    $user_unlock = Db::name('user_unlock_region')
                        ->where('user_id',$order['user_id'])
                        ->where('region_name',$v['city'])
                        ->find();
                    if(empty($user_unlock)){
                        //不存在的话则进行添加
                        $temp['user_id'] = $order['user_id'];
                        $temp['region_name'] = $v['city'];
                        $temp['is_unlock_question'] = $v['is_unlock_question'];
                        $temp['is_unlock_skill'] = $v['is_unlock_skill'];
                        $temp['create_at'] = currentTime();
                        Db::name('user_unlock_region')->insert($temp);
                    }else{
                        //存在的时候直接进行更新
                        if($user_unlock['is_unlock_question'] == 0) {
                            $temp['is_unlock_question'] = $v['is_unlock_question'];
                        }
                        if($user_unlock['is_unlock_skill'] == 0) {
                            $temp['is_unlock_skill'] = $v['is_unlock_skill'];
                        }
                        $temp['update_at'] = currentTime();
                        Db::name('user_unlock_region')
                            ->where('id',$user_unlock['id'])
                            ->update($temp);
                    }
                }
                //更新订单状态到已支付
                Db::name('pay_order')
                    ->where('id',$order['id'])
                    ->update(['is_pay'=>1,'pay_at'=>currentTime()]);

                $data = ['result' => 1, 'message_id' => 'success'];
                return json($data);
            }
        }catch (Exception $e){
            Log::info('发生异常：'.$e->getMessage());
            Log::info('发生异常：'.$e->getTraceAsString());
            return 'fail';
        }
    }



}